package org.example.impl;

import org.example.DAO.UserDao;
import org.example.entity.User;
import org.example.Util.PasswordUtil;

import javax.sql.DataSource;
import java.sql.*;

public class UserDaoImpl implements UserDao {
    private final DataSource dataSource;

    public UserDaoImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public boolean isUsernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }
    }
    @Override
    public User getUserByUsername(String username) throws SQLException {
        String sql = "SELECT id, username, password, email, phone FROM users WHERE username = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    return user;
                }
            }
        }
        return null;
    }

    @Override
    public boolean updateUserInfo(User user) throws SQLException {
        String sql = "UPDATE users SET " +
                "gender = ?, email = ?, phone = ?, " +
                "birthday = ?, province = ?, city = ? " +
                "WHERE id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, user.getGender());
            pstmt.setString(2, user.getEmail()); // 确保这行正确设置email
            pstmt.setString(3, user.getPhone());
            pstmt.setString(4, user.getBirthday());
            pstmt.setString(5, user.getProvince());
            pstmt.setString(6, user.getCity());
            pstmt.setInt(7, user.getId());

            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        }
    }

    @Override
    public boolean isEmailExists(String email) throws SQLException {
        String sql = "SELECT COUNT(*) FROM users WHERE email = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, email);
            try (ResultSet rs = pstmt.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }
    }

    @Override
    public boolean registerUser(User user) throws SQLException {
        String sql = "INSERT INTO users (username, password, gender, email, phone, avatar, birthday, province, city) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            // 注册时加密密码
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getGender());
            pstmt.setString(4, user.getEmail());
            pstmt.setString(5, user.getPhone());

            if (user.getAvatar() != null) {
                pstmt.setBlob(6, user.getAvatar());
            } else {
                pstmt.setNull(6, Types.BLOB);
            }

            pstmt.setString(7, user.getBirthday());
            pstmt.setString(8, user.getProvince());
            pstmt.setString(9, user.getCity());

            return pstmt.executeUpdate() > 0;
        }
    }



    @Override
    public boolean changePassword(String username, String oldPassword, String newPassword) throws SQLException {
        String checkSql = "SELECT password FROM users WHERE username = ?";
        String updateSql = "UPDATE users SET password = ? WHERE username = ?";

        try (Connection conn = dataSource.getConnection()) {
            // 获取用户当前密码
            try (PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
                checkStmt.setString(1, username);
                try (ResultSet rs = checkStmt.executeQuery()) {
                    if (rs.next()) {
                        String hashedPassword = rs.getString("password");
                        // 验证原密码
                        if (PasswordUtil.verifyPassword(oldPassword, hashedPassword)) {
                            // 原密码正确，加密新密码并更新
                            String encryptedNewPassword = PasswordUtil.encryptPassword(newPassword);
                            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                                updateStmt.setString(1, encryptedNewPassword);
                                updateStmt.setString(2, username);
                                return updateStmt.executeUpdate() > 0;
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
    @Override
    public boolean updatePassword(String account, String newPassword) throws SQLException {
        String sql = "UPDATE users SET password = ? WHERE username = ? OR email = ? OR phone = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, newPassword);
            stmt.setString(2, account);
            stmt.setString(3, account);
            stmt.setString(4, account);

            return stmt.executeUpdate() > 0;
        }
    }
    @Override
    public boolean resetPasswordByEmail(String email, String newPassword) throws SQLException {
        String sql = "UPDATE users SET password = ? WHERE email = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            // 加密新密码
            String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
            pstmt.setString(1, encryptedPassword);
            pstmt.setString(2, email);
            return pstmt.executeUpdate() > 0;
        }
    }
}